package tcp_proxy_middleware

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"log"
	"time"
)

// TCP QPS 统计
func TCPFlowCountModeMiddleware() func(c *TcpSliceRouterContext) {
	return func(c *TcpSliceRouterContext) {
		serviceInterface := c.Get("service")
		if serviceInterface == nil {
			c.Conn.Write([]byte("【服务不存在】service not found"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		// 统计项： 1 全站 2 服务 3 租户
		// 全站统计器
		totalCounter, err := public.FlowCounterHandler.GetCounter(public.FlowTotal)
		if err != nil {
			c.Conn.Write([]byte("获取全站统计器失败：" + err.Error()))
			c.Abort()
			return
		}
		totalCounter.Increase()
		dayCount, _ := totalCounter.GetDayData(time.Now())
		log.Printf("全站统计 qps:%v dayCount:%v", totalCounter.QPS, dayCount)
		// 服务统计器
		serviceCounter, err := public.FlowCounterHandler.GetCounter(public.FlowServicePrefix + service.Info.ServiceName)
		if err != nil {
			c.Conn.Write([]byte("获取服务统计器失败：" + err.Error()))
			c.Abort()
			return
		}
		serviceCounter.Increase()
		dayServiceCount, _ := serviceCounter.GetDayData(time.Now())
		log.Printf("服务统计 qps:%v dayCount:%v", serviceCounter.QPS, dayServiceCount)
		c.Next()
	}
}
